package service

import (
	"encoding/json"
	"project-info/src/lib"
	"project-info/src/model"
	"strconv"
)

type ResourceService struct{}

type K8sCluster struct {
	Id          uint64 `json:"id"`
	ClusterName string `json:"clusterName"`
	Config      string `json:"config"`
}

// GetK8sConfig 获取k8s配置
func (r *ResourceService) GetK8sConfig(c *lib.GinContext, item *model.Item) (*K8sCluster, error) {
	var resource model.Resource
	model.DB().Where("id = ?", item.DeployCluster).First(&resource)
	var meta map[string]interface{}
	err := json.Unmarshal(resource.Meta, &meta)
	if err != nil {
		return nil, err
	}

	k8sCluster := &K8sCluster{
		Id:          resource.Id,
		ClusterName: resource.Name,
		Config:      meta["config"].(string),
	}
	return k8sCluster, nil
}

// GetResourceNameByIds 通过ids获取资源名称
func (r *ResourceService) GetResourceNameByIds(c *lib.GinContext, ids []uint64) (map[uint64]string, error) {
	var resources []model.Resource
	err := model.DB().Select("id", "name").Where("id in ?", ids).Find(&resources).Error
	if err != nil {
		return nil, err
	}
	resourcesMap := make(map[uint64]string)
	for _, resource := range resources {
		resourcesMap[resource.Id] = resource.Name
	}
	return resourcesMap, nil
}

// GetResourceNameByItem 通过Item获取资源名称
func (r *ResourceService) GetResourceNameByItem(c *lib.GinContext, item *model.Item) (map[string]string, error) {
	envId, err := strconv.ParseUint(item.Env, 10, 64)
	if err != nil {
		c.Logger().Error("envId转换失败：" + err.Error())
		return nil, err
	}
	deployClusterId, err := strconv.ParseUint(item.DeployCluster, 10, 64)
	if err != nil {
		c.Logger().Error("deployClusterId转换失败：" + err.Error())
		return nil, err
	}

	m, err := r.GetResourceNameByIds(c, []uint64{envId, deployClusterId})
	if err != nil {
		return nil, err
	}

	var nameIds = make(map[string]string)
	for u, s := range m {
		nameIds[strconv.FormatUint(u, 10)] = s
	}
	return nameIds, nil
}
